/**
 * Created by Administrator on 2017/2/16 0016.
 */
const UserModel = require('../models/users-model.js');
const RoleModel = require('../models/roles-model.js');
const service = require('../service/service.js');
const userController = {
    /**
     * 登录
     * @param params
     * @returns {Array|{index: number, input: string}}
     */
    login (params) {
        return new Promise((resolve, reject) => {
            UserModel
                .find({
                    loginAccount: params.loginAccount,
                    password: params.loginPassword
                })
                .exec((error, doc) => {
                    if (error) {
                        reject({status: 500, message: '未知错误'});
                    } else {
                        doc.length > 0 &&
                        resolve({
                            result: { role: doc[0].roleKey.join(',') },
                            message: 'success'
                        });

                        doc.length === 0 && reject({status: 500, message: '未知错误'});
                    }
                });
        });
    },

    /**
     * 获取所有用户角色
     * @param params
     * @returns {Promise}
     */
    getAllUserRoles (params) {
        return new Promise((resolve, reject) => {
            RoleModel
                .find()
                .exec((error, docs) => {
                    if (error) {
                        reject({status: 500, message: '未知错误'})
                    }else {
                        resolve({
                            result: docs,
                            message: 'success'
                        })
                    }
                });
        });
    },

    /**
     * 根据角色获取所有用户
     * @param params
     * @returns {Promise}
     */
    getAllUsersByRole (params) {

        return new Promise((resolve, reject) => {
            UserModel
                .find({
                    role: params.role,
                    loginAccount: new RegExp(params.filterAccountPrefix)
                })
                .exec((error, doc) => {
                    if (error) {
                        reject({status: 500, message: '未知错误'});
                    }
                })
                .then((err, doc) => {
                    if (err) {
                        console.log(err);
                    } else {
                        resolve(doc);
                    }
                })
        });

    },

    /**
     * 根据角色和账号前缀，分页查询用户
     * @param params
     * @returns {Promise}
     */
    getPaginationUsersByRole (params) {
        let queryParam = params.filterAccountPrefix
            ?
        {
            roleKey: [`ROLE_${params.role}`],
            loginAccount: new RegExp(params.filterAccountPrefix)
        } :
        {
            roleKey: [`ROLE_${params.role}`]
        };
        return new Promise((resolve, reject) => {
            UserModel
                .find(queryParam, null, {skip: (params.pageNumber - 1) * params.pageSize})
                .limit(params.pageSize)
                .exec((error, doc) => {
                    if (error) {
                        reject({status: 500, message: '未知错误'});
                    }
                })
                .then((doc) => {
                    UserModel
                        .find(queryParam)
                        .count((err, count) => {
                            resolve({
                                content: doc,
                                totalSize: count
                            })
                        })
                })

        });

    },

    /**
     * 创建用户
     * @param params
     * @returns {Promise}
     */
    createUser (params) {
        return new Promise((resolve, reject) => {
            UserModel.create({
                "creatorFullName": params.creatorFullName,
                "creatorRoleName": params.creatorRoleName,
                "email": params.email,
                "enabled": true,
                "fullName": params.fullName,
                "hasRole": params.hasRole,
                "id": null,
                "loginAccount": params.loginAccount,
                "nickName": params.nickName,
                "password": params.password,
                "phone": params.phone,
                "portrait": params.portrait,
                "portrait_url": params.portrait_url,
                "rating": params.rating,
                "roleKey": params.roleKey,
                "subjects": params.subjects,
                "teachingExperience": params.teachingExperience
            }, (err) => {
                if (err) {
                    console.log(err);
                } else {
                    resolve({
                        message: 'ok',
                        result: true
                    })
                }
            })
        });

    },

    /**
     * 删除用户
     * @param params
     * @returns {Promise}
     */
    deleteUser (params) {
        return new Promise((resolve, reject) => {
            UserModel.findOneAndRemove({
                _id: params.deletingUserId
            }, null, (err) => {
                if (err) {
                    reject({ message: err, status: 500 });
                } else {
                    resolve({ message: 'success' });
                }
            })
        });
    },

    updateUserInfo () {

    }

};

module.exports = userController;